﻿from board_2048 import Board2048
import pyautogui
import pygetwindow
import numpy as np
import cv2
import pytesseract
import matplotlib.pyplot as plt
from PIL import Image


class Recognize(object):

    def __init__(self, window):
        self.window = window

    def recognize_board_row_column_obs(self, i, j):
        x = self.window.left + 28
        y = self.window.top + 318
        width = (self.window.width - 60) // 4
        # 截取窗口的图片
        start_x = x
        start_y = y

        start_x += j * width

        start_y += i * width

        padding = 10
        start_x += padding
        start_y += padding
        width -= 2 * padding
        screenshot = pyautogui.screenshot(region=(start_x, start_y, width, width))

        screenshot.save(f"./record/game1/1/{i}_{j}.png")
        img = np.array(screenshot)
        v = self.recognize_img(img)
        return v

    def recognize_board_row_column(self, i, j):
        x = self.window.left + 28
        y = self.window.top + 318
        width = (self.window.width - 60) // 4
        padding = 10
        cell_width = width - 2 * padding

        # 先截取整个窗口的图片
        full_screenshot = pyautogui.screenshot(
            region=(
                self.window.left,
                self.window.top,
                self.window.width,
                self.window.height,
            )
        )
        full_img = np.array(full_screenshot)

        # img_pil = Image.fromarray(full_img)
        # img_pil.save(f"./record/game1/1/00full.png")

        # 计算每个单元格的起始坐标
        start_x = 28 + j * width + padding
        start_y = 318 + i * width + padding
        # 从整个图片中裁剪出对应单元格的部分
        cell_img = full_img[
            start_y : start_y + cell_width, start_x : start_x + cell_width
        ]

        # # 将 NumPy 数组转换为 PIL 图像
        # cell_img_pil = Image.fromarray(cell_img)
        # # 保存图像到本地
        # cell_img_pil.save(f"./record/game1/1/{i}_{j}.png")

        v = self.recognize_img(cell_img)
        return v

    def recognize_img(self, img):

        # plt.imshow(img)
        # plt.axis('off')  # 可选：关闭坐标轴
        # plt.show()
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        pytesseract.pytesseract.tesseract_cmd = (
            r"C:\Program Files\Tesseract-OCR\tesseract.exe"
        )

        recognized_text = pytesseract.image_to_string(
            img, config=r"--oem 3 --psm 6 outputbase digits"
        )

        if recognized_text == "" and self.check_none(img):
            recognized_text = "0"

        return int(recognized_text)

    def check_none(self, img):

        # plt.imshow(img)
        # plt.axis("off")  # 可选：关闭坐标轴
        # plt.show()

        # 计算总像素数
        total_pixels = img.size

        # 使用np.unique计算每个像素值的频率
        values, counts = np.unique(img, return_counts=True)

        # 找到出现频率最高的像素
        max_frequency = np.max(counts)

        # 判断频率是否超过阈值
        if (max_frequency / total_pixels) >= 0.95:
            return True
        else:
            return False